package by.gravity.drive_track.task;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import by.gravity.common.task.CommonGsonAsyncTask;
import by.gravity.common.utils.MapUtil;
import by.gravity.drive_track.model.direction.Direction;
import by.gravity.drive_track.model.direction.Legs;
import by.gravity.drive_track.model.direction.Routes;
import by.gravity.drive_track.model.direction.Steps;

import com.google.android.gms.maps.model.LatLng;

public abstract class DirectionTask extends CommonGsonAsyncTask<Direction> {

	public DirectionTask(Context context) {
		super(context);
	}

	private void convertModel(Direction result) {
		if (result.isOkStatus()) {
			if (result.getRoutes() != null) {
				List<LatLng> pointsList = new ArrayList<LatLng>();
				Routes route = result.getRoutes().get(0);
				route.getWaypointOrder();
				List<Legs> legs = route.getLegs();
				for (int i = 0, legsSize = legs.size(); i < legsSize; i++) {
					List<Steps> steps = legs.get(i).getSteps();
					for (int j = 0, stepsSize = steps.size(); j < stepsSize; j++) {
						pointsList.addAll(MapUtil.decodePoly(steps.get(j).getPolyline().getPoints()));
					}
				}

				onComplete(pointsList, route.getWaypointOrder());
			}
		}
	}

	@Override
	protected void onSuccess(Direction result) {
		convertModel(result);
	}

	@Override
	protected Type getType() {
		return Direction.class;
	}

	public abstract void onComplete(List<LatLng> result, List<Integer> wayPointOrder);

	public abstract void onError();
}
